﻿using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Net;

namespace StudyCompanion.Commons.Image;

public class CaptchaModel
{
    public int X { get; set; }
    public int Y { get; set; }
    public System.Drawing.Image Background { get; set; }
    public System.Drawing.Image Slide { get; set; }
}

public class Captcha64Model
{
    public int X { get; set; }
    public int Y { get; set; }
    public string Background { get; set; }
    public string Slide { get; set; }
}

public class Config
{
    /// <summary>
    ///     矩形宽
    /// </summary>
    public static int l = 42;

    /// <summary>
    ///     圆形半径
    /// </summary>
    public static int r = 9;

    /// <summary>
    ///     圆形直径
    /// </summary>
    public static int d = r * 2;

    /// <summary>
    ///     计算圆形与矩形交接三角形边
    /// </summary>
    public static int a = (int)(r * Math.Sin(Math.PI * (50 / 180f)));

    public static int b = (int)(r * Math.Cos(Math.PI * (50 / 180f)));
    public static int c = r - a;

    /// <summary>
    ///     滑块边框
    /// </summary>
    public static int blod = 2;

    /// <summary>
    ///     水印
    /// </summary>
    public static string watermarkText = "用工宝";

    /// <summary>
    ///     是否显示水印
    /// </summary>
    public static bool showWatermark = true;
}

public class ImgFormat
{
    private static readonly Dictionary<string, string> Formats = new()
    {
        { "b96b3caa-0728-11d3-9d7b-0000f81ef32e", "MemoryBmp" },
        { "b96b3cab-0728-11d3-9d7b-0000f81ef32e", "Bmp" },
        { "b96b3cac-0728-11d3-9d7b-0000f81ef32e", "Emf" },
        { "b96b3cad-0728-11d3-9d7b-0000f81ef32e", "Wmf" },
        { "b96b3cae-0728-11d3-9d7b-0000f81ef32e", "Jpeg" },
        { "b96b3caf-0728-11d3-9d7b-0000f81ef32e", "Png" },
        { "b96b3cb0-0728-11d3-9d7b-0000f81ef32e", "Gif" },
        { "b96b3cb1-0728-11d3-9d7b-0000f81ef32e", "Tiff" },
        { "b96b3cb2-0728-11d3-9d7b-0000f81ef32e", "Exif" },
        { "b96b3cb5-0728-11d3-9d7b-0000f81ef32e", "Icon" }
    };

    public static ImageFormat FormatFromGuid(ImageFormat format)
    {
        return FormatFromGuid(format.Guid);
    }

    public static ImageFormat FormatFromGuid(Guid guid)
    {
        return FormatFromGuid(guid.ToString());
    }

    public static ImageFormat FormatFromGuid(string guid)
    {
        if (Formats.ContainsKey(guid))
        {
            var name = Formats[guid];
            ImageFormat format = null;
            switch (name)
            {
                case "MemoryBmp":
                    format = ImageFormat.MemoryBmp;
                    break;
                case "Bmp":
                    format = ImageFormat.Bmp;
                    break;
                case "Emf":
                    format = ImageFormat.Emf;
                    break;
                case "Wmf":
                    format = ImageFormat.Wmf;
                    break;
                case "Gif":
                    format = ImageFormat.Gif;
                    break;
                case "Jpeg":
                    format = ImageFormat.Jpeg;
                    break;
                case "Png":
                    format = ImageFormat.Png;
                    break;
                case "Tiff":
                    format = ImageFormat.Tiff;
                    break;
                case "Exif":
                    format = ImageFormat.Exif;
                    break;
                case "Icon":
                    format = ImageFormat.Icon;
                    break;
            }

            return format;
        }

        return null;
    }


    public static string NameFromGuid(ImageFormat format)
    {
        return NameFromGuid(format.Guid);
    }

    public static string NameFromGuid(Guid guid)
    {
        return NameFromGuid(guid.ToString());
    }

    public static string NameFromGuid(string guid)
    {
        return Formats.TryGetValue(guid, out var fromGuid) ? fromGuid : string.Empty;
    }
}

public class Captcha
{
    public static Captcha64Model GenerateBase64(string url, Action<CaptchaModel> action)
    {
        var model = Generate(url);
        if (model == null) return null;
        action(model);
        return new Captcha64Model
        {
            X = model.X,
            Y = model.Y,
            Background = ImageToBase64(model.Background, ImageFormat.Jpeg),
            Slide = ImageToBase64(model.Slide, ImageFormat.Png)
        };
    }

    /// <summary>
    ///     生成验证码
    /// </summary>
    /// <returns></returns>
    public static CaptchaModel Generate(string url)
    {
        var image = BgImage(url);
        if (image != null)
        {
            var l = Config.l;
            var d = Config.d;
            var width = image.Width;
            var height = image.Height;
            var x = RandomNext(width / 3, width - d - l - 10); //初始x
            var y = RandomNext(10 + d, height - l - 10);
            //初始y
            var path = GetSliderPath(x, y);
            var g = GetGraphics(image);

            //水印
            if (Config.showWatermark)
            {
                var font = new Font("宋体", 12, FontStyle.Bold);
                var size = g.MeasureString(Config.watermarkText, font);
                var Plogo = new Point((int)(width - size.Width - 5), (int)(height - size.Height - 5));
                var color = image.GetPixel(Plogo.X, Plogo.Y);
                var bru = new SolidBrush(AntiColor(color));
                g.DrawString(Config.watermarkText, font, bru, Plogo);
            }

            var pen = new Pen(Color.FromArgb(200, 255, 255, 255), 2);
            g.DrawPath(pen, path);
            var slider = CaptureSlider(image, path, x, height);
            var brush = new SolidBrush(Color.FromArgb(100, 255, 255, 255));
            g.FillPath(brush, path);
            g.Save();
            g.Dispose();
            return new CaptchaModel
            {
                X = x,
                Y = y,
                Background = image,
                Slide = slider
            };
        }

        return null;
    }

    /// <summary>
    ///     获取图片Graphics
    /// </summary>
    /// <param name="image"></param>
    /// <returns></returns>
    private static Graphics GetGraphics(System.Drawing.Image image)
    {
        var g = Graphics.FromImage(image);
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.CompositingQuality = CompositingQuality.HighQuality;
        g.InterpolationMode = InterpolationMode.High;
        return g;
    }

    /// <summary>
    ///     获取滑块path
    /// </summary>
    private static GraphicsPath GetSliderPath(int x, int y)
    {
        var l = Config.l;
        var r = Config.r;
        var b = Config.b;
        var c = Config.c;
        var d = Config.d;
        var blod = Config.blod;
        var path = new GraphicsPath(FillMode.Winding);
        var Pa = new Point(x, y);
        var Pb = new Point(x + l / 2 - b, y - c + blod);
        var Pd = new Point(x + l, y);
        var Pe = new Point(Pd.X + c - blod, y + l / 2 - b);
        var Pg = new Point(Pd.X, y + l);
        var Ph = new Point(x, y + l);
        var Pj = new Point(x + c - blod, Pe.Y);
        path.AddLine(Pa, Pb);
        path.AddArc(x + l / 2 - r, y - d, d, d, 130f, 280f);
        path.AddLines(new[] { Pd, Pe });
        path.AddArc(x + l, y + l / 2 - r, d, d, 220f, 280f);
        path.AddLines(new[] { Pg, Ph });
        path.AddArc(x, y + l / 2 - r, d, d, 140f, -280f);
        path.AddLine(Pj, Pa);
        return path;
    }

    /// <summary>
    ///     获取滑块区域
    /// </summary>
    /// <param name="image"></param>
    /// <param name="path"></param>
    /// <param name="x"></param>
    /// <param name="height"></param>
    /// <returns></returns>
    private static System.Drawing.Image CaptureSlider(System.Drawing.Image image, GraphicsPath path, int x,
        int height)
    {
        var concave = new Bitmap(image.Width, image.Height);
        var g = GetGraphics(concave);
        var brush = new TextureBrush(image);
        g.Clear(Color.Transparent);
        g.FillPath(brush, path);
        g.Dispose();
        return CaptureImage(concave, x, height);
    }

    /// <summary>
    ///     裁剪图片
    /// </summary>
    /// <param name="fromImage"></param>
    /// <param name="offsetX"></param>
    /// <param name="height"></param>
    /// <returns></returns>
    private static System.Drawing.Image CaptureImage(System.Drawing.Image fromImage, int offsetX, int height)
    {
        var width = Config.l + Config.d + Config.blod;
        var bitmap = new Bitmap(width, height);
        var g = GetGraphics(bitmap);
        g.DrawImage(fromImage, 0, 0, new Rectangle(offsetX, 0, width, height), GraphicsUnit.Pixel);
        g.Dispose();
        return bitmap;
    }

    /// <summary>
    ///     生成随机数
    /// </summary>
    /// <param name="min"></param>
    /// <param name="max"></param>
    /// <returns></returns>
    private static int RandomNext(int min, int max)
    {
        var random = new Random(Guid.NewGuid().GetHashCode());
        return random.Next(min, max);
    }

    /// <summary>
    ///     取反色
    /// </summary>
    /// <param name="color"></param>
    /// <returns></returns>
    public static Color AntiColor(Color color)
    {
        if (color.R > 128 && color.G > 128 && color.B > 128)
            return Color.Black;
        return Color.White;
    }

    /// <summary>
    ///     获取背景图
    /// </summary>
    /// <returns></returns>
    private static Bitmap BgImage(string url)
    {
        var web = new WebClient();
        var stream = web.OpenRead(url);
        var bitmap = (Bitmap)System.Drawing.Image.FromStream(stream);
        return bitmap;
    }

    /// <summary>
    ///     base64转图片
    /// </summary>
    /// <param name="base64string"></param>
    /// <returns></returns>
    public static Bitmap Base64ToImage(string base64string)
    {
        var b = Convert.FromBase64String(base64string);
        var ms = new MemoryStream(b);
        var bitmap = new Bitmap(ms);
        return bitmap;
    }

    /// <summary>
    ///     图片转base64
    /// </summary>
    /// <param name="image"></param>
    /// <param name="format"></param>
    /// <returns></returns>
    public static string ImageToBase64(System.Drawing.Image image, ImageFormat format)
    {
        if (image == null) return string.Empty;
        var strbaser64 = "";
        try
        {
            var head = "";
            var formatName = ImgFormat.NameFromGuid(format);
            head = $"data:image/{formatName.ToLower()};base64,";
            var ms = new MemoryStream();
            image.Save(ms, format);
            var arr = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(arr, 0, (int)ms.Length);
            ms.Close();
            strbaser64 = head + Convert.ToBase64String(arr);
        }
        catch (Exception)
        {
            throw new Exception("Something wrong during convert!");
        }

        return strbaser64;
    }

    /// <summary>
    ///     验证滑块
    /// </summary>
    /// <param name="ux">服务器</param>
    /// <param name="x">客户端</param>
    /// <returns></returns>
    public static bool Check(int ux, int x)
    {
        var difX = ux - x;
        return difX >= 0 - (Config.blod + 2) && difX <= Config.blod + 2;
    }
}